/**
 * 
 */
package com.dy.dataprocess.general.tools.config.service.impl;

import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.dy.dataprocess.general.tools.config.dal.mapper.BizConfigMapper;
import com.dy.dataprocess.general.tools.config.model.BizConfig;
import com.dy.dataprocess.general.tools.config.service.BizConfigService;
import com.google.common.collect.Maps;

import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

/**
 * @author leiruiqi
 *
 */
@Service("bizConfigService")
public class BizConfigServiceImpl implements BizConfigService {

	@Resource
	private BizConfigMapper bizConfigMapper;
	
	private Map<String,String> configMaplocalCache = null;

	@Override
	public String getValueByKeyFromLocalCache(String bizKey) {
		return configMaplocalCache.get(bizKey);
	}

	@Override
	public Map<String, String> getValueByKeysFromLocalCache(Collection<String> keys) {
		Map<String,String> tempMap = Maps.newHashMap();
		for(String key:keys){
			String tempValue = configMaplocalCache.get(key);
			tempMap.put(key, tempValue);
		}
		return tempMap;
	}

	@Override
	public List<BizConfig> queryAll() {
		return bizConfigMapper.selectAll();
	}

	@Override
	public void save(BizConfig bizConfig) {
		BizConfig old = getByKey(bizConfig.getBizKey());
		if(old==null){
			bizConfigMapper.insert(bizConfig);
		}else{
			Example condition = new Example(BizConfig.class);
			//Condition condition = new Condition(BizConfig.class);
			condition.createCriteria().andEqualTo("bizKey", old.getBizKey());
			bizConfigMapper.updateByExample(bizConfig, condition);
		}
		
	}

	@Override
	public void delByKey(String bizKey) {
		
		Example condition = new Example(BizConfig.class);
		condition.createCriteria().andEqualTo("bizKey", bizKey);
		bizConfigMapper.deleteByExample(condition);
	}
	
	

	@Override
	public BizConfig getByKey(String bizKey) {
		BizConfig bizConfig = new BizConfig();
		bizConfig.setBizKey(bizKey);
		return bizConfigMapper.selectOne(bizConfig);
	}

	@PostConstruct
	@Override
	public void refresh() {
		Map<String,String> tmpMap = Maps.newHashMap();
		List<BizConfig> list = this.queryAll();
		for(BizConfig bizConfig:list){
			tmpMap.put(bizConfig.getBizKey(), bizConfig.getBizValue());
		}
		this.configMaplocalCache = tmpMap;
	}
	
}
